// Copyright (c) Appeon
// The following has been modified by Appeon under compliance with the Apache 2.0 license from the original work

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Data;
using System.Data.Common;
using Microsoft.Data.SqlClient;
using JetBrains.Annotations;

namespace SnapObjects.Data.SqlServer
{
    public class SqlServerStringTypeMapping : StringTypeMapping
    {
        private readonly int _maxSpecificSize;
        private readonly SqlDbType? _sqlDbType;
        private readonly DataContextOptions _options;

        /// <summary>
        ///     Initializes a new instance of the <see cref="SqlServerStringTypeMapping" /> class.
        /// </summary>
        /// <param name="dbTypeName"> The name of the database type. </param>
        /// <param name="sqlDbType"> The <see cref="DbType" /> to be used. </param>
        /// <param name="unicode"> A value indicating whether the type should handle Unicode data or not. </param>
        /// <param name="size"> The size of data the property is configured to store, or null if no size is configured. </param>
        public SqlServerStringTypeMapping(
            [NotNull] string dbTypeName,
            SqlDbType? sqlDbType = null,
            bool unicode = false,
            int? size = null,
            DataContextOptions options = null)
            : base(dbTypeName, GetDbType(unicode), unicode, size)
        {
            _options = options;
            _sqlDbType = sqlDbType;
            _maxSpecificSize = CalculateSize(unicode, size);
        }

        private static DbType? GetDbType(bool unicode)
        {
            if (!unicode)
            {
                return System.Data.DbType.AnsiString;
            }

            return null;
        }

        private static int CalculateSize(bool unicode, int? size)
        {
            return unicode
                           ? size.HasValue && size < 4000 ? size.Value : 4000
                           : size.HasValue && size < 8000 ? size.Value : 8000;
        }

        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public override TypeMapping Clone(string dbTypeName, int? size)
        {
            return new SqlServerStringTypeMapping(dbTypeName, _sqlDbType, this.IsUnicode, size, _options);
        }

        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        protected override void ConfigureParameter(DbParameter parameter, IAdoDbParameter adoDbParameter)
        {
            // For strings and byte arrays, set the max length to the size facet if specified, or
            // 8000 bytes if no size facet specified, if the data will fit so as to avoid query cache
            // fragmentation by setting lots of different Size values otherwise always set to
            // -1 (unbounded) to avoid SQL client size inference.

            var tmpMaxSize = _maxSpecificSize;

            if (parameter is SqlParameter sqlParameter)
            {
                if (_sqlDbType.HasValue)
                {
                    sqlParameter.SqlDbType = _sqlDbType.Value;
                }

                var value = parameter.Value;
                var length = (value as string)?.Length ?? (value as byte[])?.Length;

                parameter.Size = value == null || value == DBNull.Value || (length != null && length <= tmpMaxSize)
                    ? tmpMaxSize
                    : -1;
            }
        }

        /// <summary>
        ///     Generates the SQL representation of a literal value.
        /// </summary>
        /// <param name="value">The literal value.</param>
        /// <returns>
        ///     The generated string.
        /// </returns>
        protected override string GenerateNonNullSqlLiteral(object value)
        {
            return this.IsUnicode
                ? $"N'{this.EscapeSqlLiteral((string)value)}'" // Interpolation okay; strings
                : $"'{this.EscapeSqlLiteral((string)value)}'";
        }
    }
}
